module EasyForm
  module Wrappers
    class Many
      attr_reader :namespace, :components, :defaults

      def initialize(namespace, components, defaults = {})

        @namespace, @components, @defaults = namespace, components, defaults
        @defaults[:tag]   = :div unless @defaults.key?(:tag)
        @defaults[:class] = Array(@defaults[:class])
      end

      def render(input)
        content = ''.html_safe
        options = input.options

        components.each do |component|
          next if options[component.namespace] == false
          rendered = component.render(input)
          content.safe_concat(rendered.to_s) if rendered
        end
        wrap(input, options, content)
      end

      def find(name)
        return self if namespace == name

        components.each do |c|
          if c.is_a?(Symbol)
            return nil if c == namespace
          elsif value = c.find(name)
            return value
          end
        end

        nil
      end

      private
      def wrap(input, options, content)
        return content if options[namespace] == false
        return if defaults[:unless_blank] && content.empty?

        tag = (namespace && options[:"#{namespace}_tag"]) || defaults[:tag]
        return content unless tag

        klass = html_classes(input, options)
        opts = html_options(options)
        opts[:class] = (klass << opts[:class]).join(' ').strip unless klass.empty?
        input.template.content_tag(tag, content, opts)
      end

      def html_options(options)
        (defaults[:html] || {}).merge(options[:"#{namespace}_html"] || {})
      end

      def html_classes(input, options)
        defaults[:class].dup
      end
    end
  end
end